package com.geek.game.manager.agent.base.mvc;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.geek.game.manager.agent.base.utils.JacksonUtil;
import com.geek.game.manager.agent.base.utils.MD5Util;
import com.geek.game.manager.agent.model.Manager;

import ydh.cicada.api.SetAndGet;
import ydh.cicada.dao.JdbcDao;
import ydh.cicada.query.QueryObject;

@Controller
@RequestMapping(value="base")
public class BaseController {

	@Resource
    protected HttpServletRequest request;
    @Resource
    protected HttpServletResponse response;
    @Resource
    protected HttpSession session;
    
	protected BaseResult returnResult=null;
	
	protected Date nowDate=new Date();
	
	protected static Log log= LogFactory.getLog(BaseController.class);
	
	@Autowired
	private JdbcDao dao;
	
	@SuppressWarnings("rawtypes")
	@ModelAttribute("returnResult")
	public void setReturnResult(HttpServletRequest request,Model model,HttpServletResponse response) throws UnsupportedEncodingException{
			Manager user=(Manager)session.getAttribute(request.getLocalAddr());
			if(user!=null && StringUtils.isNotBlank( user.getId())){
				session.setAttribute(request.getLocalAddr(), QueryObject.select("t.user_id id,t.*",Manager.class)
						.from("t_manager t")
						.cond("t.user_id").equ(user.getId())
						.firstResult(dao));
			}
			returnResult=new BaseResult();
			model.addAttribute("Context",basePath());
			model.addAttribute("ContextPath",request.getContextPath());
			model.addAttribute("gameName","友友扎金花");
	}
	
    @ExceptionHandler
    @ResponseBody
    public String exception(HttpServletRequest request, Exception e) {  
    	returnResult=new BaseResult();
    	returnResult.setError(true);
    	returnResult.setMsg(e.getClass().getName()+"--:--"+e.getMessage());
    	if(e instanceof BadSqlGrammarException){    		
    		log.error("SQL错误："+((BadSqlGrammarException)e).getSql()+
    				"\n Cause:"+((BadSqlGrammarException)e).getCause());
    	}
    	if(e instanceof NullPointerException){
    		log.error(e.getStackTrace());
    		returnResult.setMsg("空指针异常！");
    	}
		return resultVal();
    }  
    @RequestMapping("/difined")
    public String difined(HttpServletRequest request,HttpServletResponse response){
    	System.err.println("difined");
    	writeJson(response);
    	return null;
    }

    private void writeJson(HttpServletResponse response){
    	 PrintWriter out = null;
         try {
             response.setCharacterEncoding("UTF-8");
             response.setContentType("application/json; charset=utf-8");
             out = response.getWriter();
             out.write(resultVal()==null?"{}":resultVal());
         } catch (IOException e) {
             e.printStackTrace();
         } finally {
             if (out != null) {
                 out.close();
             }
         }
    }
    
	public BaseResult getReturnResult() {
		return returnResult;
	}

	public void setReturnResult(BaseResult returnResult) {
		this.returnResult = returnResult;
	}

	
	public String resultVal(){
		return JacksonUtil.getJsonFromObject(this.returnResult);
	}

	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	public HttpServletResponse getResponse() {
		return response;
	}

	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}

	public HttpSession getSession() {
		return session;
	}
	/**
	 * 获取当前路径
	 * @return
	 */
	protected String basePath(){
		return request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/";
	}
}
